#include "map.h"
#include <malloc.h>
#include <stdio.h>
#include <memory.h>

using namespace std;

Map::Map(){
    mW = 0;
    mH = 0;
    mData = 0;
}

Map::Map(int w, int h){ 
    mW = w;
    mH = h;
    mData = (int*)malloc(mW*mH);
    memset(mData,0,mW*mH);
}

Map::~Map(){
    free(mData);
}

void Map::load(char *name){
    FILE *f = fopen(name,"r");
    if(f){
        fseek(f,6,SEEK_SET);
        fread(&mW,sizeof(int),1,f);
        fread(&mH,sizeof(int),1,f);
        mData = (int*)malloc(mW*mH);
        fread(mData,mW*mH,1,f);
        fclose(f);
    }
}

void Map::save(char *name){
    FILE *f = fopen(name,"wb");
    if(f){
        fwrite("BWMAP1",6,1,f);
        fwrite(&mW,sizeof(int),1,f);
        fwrite(&mH,sizeof(int),1,f);
        fwrite(mData,mW*mH,1,f);
        fclose(f);
    }
}

void Map::setTile(int x,int y,int tile){
    mData[x+y*mW] = tile;
}
